var timerElements;
var timeLeft;
var counter = null;

//This countdown function is called once after loading a page which contains 1 or more auction-items
//After which this function will call itself every second
//
//The counter is always stopped in the function fillContent(text, area) 
//before a new one is called, but turning it off before a new page is loaded may reduce browser CPU usage.
//
//Any new function that "loads a new page" but does not call doAjaxRequest or doAjaxPostRequest,
//should contain the following line of code:
//if(counter !=null) clearTimeout(counter); //We don't need to keep counting if a new page is going to be loaded (see countdown.js) 
//
//It is therefore vital that the comments below are kept up to date in regards to this optimisation.
//
//Loading a different page should turn off the automatic callback before a new request is made to the server 
//The line of code code that does this is found in script.js in the following methods:
//-doAuctionSearch(searchTarget)
//-doLoadAccount()
//-doAjaxRequest(page, area)
//-doAjaxPostRequest(page, area, postParameters, enctype)
function countdown(hide){
	for(var i=0; i<timerElements.length; i++) {
		var time = timeLeft[i];
		var days=Math.floor(time/86400);
		var hours=Math.floor((time-days*86400)/3600);
		var minutes=Math.floor((time-days*86400-hours*3600)/60);
		var seconds=Math.floor(time-days*86400-hours*3600-minutes*60);
		var timestring = "";
		if(days > 0)
			timestring=days+":"+hours+":"+minutes+":"+seconds;
		else if (hours > 0)
			timestring=hours+":"+minutes+":"+seconds;
		else if (minutes > 0)
			timestring=minutes+":"+seconds;
		else if (seconds > 0)
			timestring=seconds;
		else if(seconds == 0) { 
			timestring = 0;
		}
		timerElements[i].innerHTML=timestring;
		if(time != 0) {
			timeLeft[i]--;
		} else {
			if(hide == "true") endAuctions(true);
			else endAuctions(false);
		}
	}
	if(timerElements.length>0)
		counter = setTimeout("countdown('"+hide+"')",1000);
}

//Remove expired auctions from the countdown variables and hide them if nescesary
function endAuctions(deleteAuction) {
	for(var i=0;i<timerElements.length;i++) {
		if(timeLeft[i] == 0) {
			if(deleteAuction) timerElements[i].parentNode.style.display = "none";
			else timerElements[i].innerHTML = "Expired";
			timerElements.splice(i,1);
			timeLeft.splice(i,1);
			i--;
		}
	}
}